﻿using Microsoft.AspNetCore.Mvc;
using up6.db.model;
using up6.utils;
using Up6.core.Up6Manager.Models.Req;

namespace up6.db.biz;

/// <summary>
/// Web安全模板
/// </summary>
public class WebSafe
{
    /// <summary>
    /// 难证token
    /// </summary>
    /// <param name="token"></param>
    /// <param name="f"></param>
    /// <param name="action">动作：init,block</param>
    /// <returns></returns>
    public bool validToken(string token, FileInf f, string action = "init")
    {
        if (ConfigReader.securityToken())
        {
            if (string.IsNullOrEmpty(token.Trim())) return false;
            CryptoTool ct = new CryptoTool();
            return ct.token(f, action) == token;
        }
        return true;
    }

    public void downToken(FileInf f)
    {
        if (string.IsNullOrEmpty(f.token)) return;
        string[] arr = {
                f.id,
                //pathSvr,
                f.blockIndex.ToString(),
                f.blockOffset.ToString()
            };
        CryptoTool ct = new CryptoTool();
        var tokenSvr = ct.aes_cbc_pkcs(Md5Tool.calc(string.Join(",", arr)), false);
        //验证失败
        if(f.token!=tokenSvr)
        {
            var ret = new
            {
                msg = "web safe valid fail",
                id = f.id,
                pathSvr = f.pathSvr,
                blockIndex = f.blockIndex,
                blockOffset = f.blockOffset,
                token = f.token,
            };
            throw new Up6Exception(new JsonResult(ret));
        }
    }
}